const { app, Menu, Tray,shell, Notification ,BrowserWindow} = require('electron');
const path = require('path');
var sudo = require('sudo-prompt');
const execSync = require("child_process").execSync;
const NOTIFICATION_TITLE = '温馨提示'
const NOTIFICATION_BODY = '检测到AirDrop开启🔛，可选择点击定栏关闭！'
let tray = null;
let  CONTEXT_MENU = null;
var SUDO_OPTION = {
  name: 'airdropkiller',
  icns: getPath('ff_open.png')
};
let mainWindow = null;
let SELF_OPEN = false;
let HAS_NOTIFCE = false;
app.whenReady().then(() => {
  tray = new Tray(getPath(`ff_open.png`));
  CONTEXT_MENU = Menu.buildFromTemplate([
    { label: 'Disabled AWDL/AirDrop@@', type: 'radio' , click: function() {handlerAirDrop("OFF");}},
    { label: 'Enabled AirDrop@@', type: 'radio' , click: function() {handlerAirDrop("ON");}},
    { label: 'About AirDrop Killer@@', type: 'normal' , click: function() {handlerAbout();}},
    { label: 'Quit', type: 'normal' , click: function() {handlerQuit();}}
  ])
  tray.setToolTip('AirDrop状态小工具😊')
  tray.setContextMenu(CONTEXT_MENU);
  intervalCheckStatus()
})

function handlerQuit() {
  app.quit();
}

function handlerAbout() {
  mainWindow = new BrowserWindow({ width: 500
    , height: 400
    ,webPreferences: {nodeIntegration: true}
    ,resizable: false
    ,show: false
  });

  // and load the index.html of the app.
  mainWindow.loadFile(path.join(__dirname, `../renderer/main_window//index.html`));
  mainWindow.show();
  mainWindow.on('close', function(e) { 
    
    if (!mainWindow.isVisible()) {
      app.quit();
    } else {
      e.preventDefault();
      mainWindow.hide();
    }
});
}

function handlerAirDrop(type) {
    if (type == 'OFF') {
      executeWithEletronSudo('ifconfig awdl0 down', () => {
        SELF_OPEN=false;
        HAS_NOTIFCE = false;
      });
    } else if (type == "ON") {
      SELF_OPEN = true;
      executeWithEletronSudo('ifconfig awdl0 up', () => {

      });
    }
}

function showNotification () {
  new Notification({ title: NOTIFICATION_TITLE, 
    body: NOTIFICATION_BODY,
    icon: getPath('ff_open.png')
  }).show();
  HAS_NOTIFCE = true
}
/**
 * flag-1, airdrop关闭状态
 * flag-0 airdrop打开状态
 * @param {*} flag 
 */
function handlerContextMenuSelect(flag) {
  if (flag == 1) {
    CONTEXT_MENU.items[1].checked =false;
    CONTEXT_MENU.items[0].checked =true;
    tray.setImage(getPath(`ff_open.png`));
  } else {
    CONTEXT_MENU.items[0].checked =false;
    CONTEXT_MENU.items[1].checked =true;
    tray.setImage(getPath(`ff_close.png`));
    if (!SELF_OPEN && !HAS_NOTIFCE) {
      showNotification();
    }
  }
}

function getPath(fileName) {
  //return isDev ? path.join(__dirname, `../../src/assets/${fileName}`) : path.join(__dirname, `./${fileName}`);
  return  path.join(__dirname, `./assets/${fileName}`);

}

function intervalCheckStatus() {
  checkAirDrop();
  setInterval(() =>{
    checkAirDrop();
  }, 3 * 1000);
}

function checkAirDrop() {
  let result = execSync('ifconfig awdl0').toString();
  if (result.indexOf('status: active') > 0) {
    handlerContextMenuSelect(0);
  } else if (result.indexOf('status: inactive') > 0) {
    handlerContextMenuSelect(1);
  }
}

function executeWithEletronSudo(command, callback) {
    sudo.exec(command, SUDO_OPTION,
        function(error, stdout, stderr) {
            if (error) {
                console.log(`error: ${error}`);
                return;
            }
            callback();
        }
    );
}
